import { Table, Modal, Form, Input, Tag, Typography, Descriptions, Divider, Upload, Button, message, Select, Space, Spin } from '@/utils/antd-imports';
import { MoneyCollectOutlined, UploadOutlined, PaperClipOutlined, CheckSquareOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import { paymentApi } from '@/api/paymentApi';















const { Text } = Typography;
const { Option } = Select;

const PaymentTab = ({ projectId, projectCode, settlements, onPayment }) => {
  const [form] = Form.useForm();
  const [paymentVisible, setPaymentVisible] = useState(false);
  const [currentRecord, setCurrentRecord] = useState(null);
  const [fileList, setFileList] = useState([]);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [batchMode, setBatchMode] = useState(false);
  const [paymentStatusFilter, setPaymentStatusFilter] = useState('all');
  const [loading, setLoading] = useState(false);
  const [paymentList, setPaymentList] = useState([]);

  // 加载回款数据
  useEffect(() => {
    if (projectId) {
      loadPayments();
    }
  }, [projectId]);

  const loadPayments = async () => {
    if (!projectId) return;
    
    setLoading(true);
    try {
      const response = await paymentApi.getPaymentsByProjectId(projectId);
      if (response.code === 200) {
        setPaymentList(response.data || []);
      } else {
        message.error(response.message || '加载回款记录失败');
      }
    } catch (error) {
      console.error('加载回款记录失败:', error);
      message.error('加载回款记录失败');
    } finally {
      setLoading(false);
    }
  };

  // 回款状态选项
  const paymentStatusOptions = [
    { label: '待回款', value: 'unpaid' },
    { label: '部分回款', value: 'partial_paid' },
    { label: '已回款', value: 'paid' }
  ];

  // 处理回款
  const handlePayment = (record) => {
    setCurrentRecord(record);
    form.setFieldsValue({
      paymentAmount: Math.min(
        record.invoiceAmount || record.totalAmount,
        (record.invoiceAmount || record.totalAmount) - (record.paidAmount || 0)
      )
    });
    setPaymentVisible(true);
  };

  // 批量回款
  const handleBatchPayment = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一条记录');
      return;
    }
    setPaymentVisible(true);
  };

  // 提交回款
  const submitPayment = async () => {
    form.validateFields().then(async (values) => {
      try {
        setLoading(true);
        
        // 准备回款数据
        const paymentData = {
          projectId: projectId,
          amount: values.paymentAmount,
          paymentDate: new Date().toISOString().split('T')[0],
          paymentStatus: '已到账',
          remark: values.note,
          voucherUrl: fileList.map(file => file.url || '#').join(',')
        };

        if (batchMode) {
          // 批量回款
          const selectedSettlements = settlements.filter(item => selectedRowKeys.includes(item.id));
          for (const item of selectedSettlements) {
            await paymentApi.createPayment({
              ...paymentData,
              amount: item.totalAmount || values.paymentAmount
            });
          }
        } else {
          // 单条回款
          await paymentApi.createPayment({
            ...paymentData,
            amount: values.paymentAmount
          });
        }

        message.success(batchMode ? '批量回款成功' : '回款成功');
        
        // 刷新数据
        await loadPayments();
        
        setPaymentVisible(false);
        form.resetFields();
        setFileList([]);
        setSelectedRowKeys([]);
        setBatchMode(false);
      } catch (error) {
        console.error('回款失败:', error);
        message.error('回款失败');
      } finally {
        setLoading(false);
      }
    });
  };

  // 处理文件上传
  const handleUploadChange = ({ fileList }) => {
    setFileList(fileList);
  };

  // 表格行选择
  const rowSelection = {
    selectedRowKeys,
    onChange: setSelectedRowKeys,
    getCheckboxProps: (record) => ({
      disabled: record.paymentStatus === 'paid' // 仅禁用已回款的记录
    })
  };

  // 筛选可回款的记录
  const filteredSettlements = settlements.filter(item => {
    if (paymentStatusFilter === 'all') return true;
    return item.paymentStatus === paymentStatusFilter;
  });

  // 表格列定义
  const columns = [
    {
      title: '回款编号',
      dataIndex: 'settlementNo',
      key: 'settlementNo',
      width: 150,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 120
    },
    {
      title: '项目名称',
      dataIndex: 'projectName',
      key: 'projectName',
      width: 150
    },
    {
      title: '子项目名称',
      dataIndex: 'subProjectName',
      key: 'subProjectName',
      width: 150
    },
    {
      title: '开始时间',
      dataIndex: 'startDate',
      key: 'startDate',
      width: 120
    },
    {
      title: '实际结束时间',
      dataIndex: 'actualEndDate',
      key: 'actualEndDate',
      width: 120,
      render: (date) => date || '-'
    },
    {
      title: '实际工时',
      dataIndex: 'actualHours',
      key: 'actualHours',
      width: 80,
      render: (hours) => hours || '-'
    },
    {
      title: '开票金额',
      dataIndex: 'invoiceAmount',
      key: 'invoiceAmount',
      width: 120,
      render: (amount, record) => (
        <Text strong>¥{(amount || record.totalAmount)?.toLocaleString()}</Text>
      )
    },
    {
      title: '已回款金额',
      dataIndex: 'paidAmount',
      key: 'paidAmount',
      width: 120,
      render: (amount) => (
        <Text type={amount > 0 ? 'success' : 'secondary'}>
          ¥{(amount || 0)?.toLocaleString()}
        </Text>
      )
    },
    {
      title: '待回款金额',
      key: 'remainingAmount',
      width: 120,
      render: (_, record) => {
        const invoiceAmount = record.invoiceAmount || record.totalAmount;
        const paidAmount = record.paidAmount || 0;
        return (
          <Text type={invoiceAmount > paidAmount ? 'danger' : 'success'}>
            ¥{(invoiceAmount - paidAmount)?.toLocaleString()}
          </Text>
        );
      }
    },
    {
      title: '回款时间',
      dataIndex: 'paymentTime',
      key: 'paymentTime',
      width: 120,
      render: (date) => date || '-'
    },
    {
      title: '回款状态',
      dataIndex: 'paymentStatus',
      key: 'paymentStatus',
      width: 120,
      render: (status) => {
        let color, icon;
        switch (status) {
          case 'paid':
            color = 'green';
            icon = <MoneyCollectOutlined />;
            break;
          case 'partial_paid':
            color = 'orange';
            icon = <MoneyCollectOutlined />;
            break;
          default:
            color = 'red';
            icon = <MoneyCollectOutlined />;
        }
        return (
          <Tag color={color} icon={icon}>
            {paymentStatusOptions.find(s => s.value === status)?.label || status}
          </Tag>
        );
      }
    },
    {
      title: '附件',
      key: 'attachments',
      width: 100,
      render: (_, record) => (
        record.paymentAttachments?.length > 0 ? (
          <Button 
            type="text" 
            icon={<PaperClipOutlined />} 
            onClick={() => {
              message.info(`查看附件: ${record.paymentAttachments.map(a => a.name).join(', ')}`);
            }}
          />
        ) : null
      )
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      fixed: 'right',  // 添加这行
      render: (_, record) => (
        record.paymentStatus !== 'paid' ? (
          <a onClick={() => handlePayment(record)}>回款</a>
        ) : null
      )
    }
  ];

  return (
    <>
      <div style={{ marginBottom: 16 }}>
        <Space>
          <Button 
            type={batchMode ? 'primary' : 'default'} 
            icon={<CheckSquareOutlined />}
            onClick={() => setBatchMode(!batchMode)}
          >
            {batchMode ? '取消批量' : '批量选择'}
          </Button>
          
          {batchMode && (
            <Button 
              type="primary" 
              onClick={handleBatchPayment}
              disabled={selectedRowKeys.length === 0}
            >
              批量回款 ({selectedRowKeys.length})
            </Button>
          )}
          
          <Select
            style={{ width: 120 }}
            value={paymentStatusFilter}
            onChange={setPaymentStatusFilter}
          >
            <Option value="all">全部状态</Option>
            <Option value="unpaid">待回款</Option>
            <Option value="partial_paid">部分回款</Option>
            <Option value="paid">已回款</Option>
          </Select>
        </Space>
      </div>

      <Spin spinning={loading}>
        <Table
          columns={columns}
          dataSource={filteredSettlements}
          rowKey="id"
          pagination={{ pageSize: 10 }}
          scroll={{ x: 1800 }}
          bordered
          rowSelection={batchMode ? rowSelection : null}
        />
      </Spin>

      {/* 回款模态框 */}
      <Modal
        title={batchMode ? '批量回款' : '项目回款'}
        visible={paymentVisible}
        onOk={submitPayment}
        onCancel={() => {
          setPaymentVisible(false);
          form.resetFields();
          setFileList([]);
        }}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
        >
          {!batchMode && currentRecord && (
            <>
              <Descriptions bordered column={1}>
                <Descriptions.Item label="项目名称">{currentRecord.projectName}</Descriptions.Item>
                <Descriptions.Item label="子项目名称">{currentRecord.subProjectName}</Descriptions.Item>
                <Descriptions.Item label="开票金额">
                  <Text strong>¥{(currentRecord.invoiceAmount || currentRecord.totalAmount)?.toLocaleString()}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="已回款金额">
                  <Text type="success">¥{(currentRecord.paidAmount || 0)?.toLocaleString()}</Text>
                </Descriptions.Item>
                <Descriptions.Item label="待回款金额">
                  <Text type="danger">
                    ¥{((currentRecord.invoiceAmount || currentRecord.totalAmount || 0) - (currentRecord.paidAmount || 0))?.toLocaleString()}
                  </Text>
                </Descriptions.Item>
              </Descriptions>
              <Divider />
            </>
          )}
          
          {batchMode && (
            <div style={{ marginBottom: 16 }}>
              <Text strong>已选择 {selectedRowKeys.length} 条记录</Text>
            </div>
          )}
          
          <Form.Item
            name="paymentAmount"
            label="本次回款金额"
            rules={[{ required: true, message: '请输入回款金额' }]}
          >
            <Input prefix="¥" type="number" />
          </Form.Item>
          
          <Form.Item label="回款凭证">
            <Upload
              fileList={fileList}
              onChange={handleUploadChange}
              beforeUpload={() => false}
            >
              <Button icon={<UploadOutlined />}>上传凭证</Button>
            </Upload>
          </Form.Item>
          
          <Form.Item
            name="note"
            label="备注"
          >
            <Input.TextArea rows={3} />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default PaymentTab;